import React, { useState, useEffect } from 'react'
import { Modal, Table, Select, Form } from 'antd'
import MultilingualInput from '@inbiz/basic/MultilingualInput';
import { getMessage, TextWidget } from '@inbiz/react';

export default function SortFieldDesc(props) {
  const { sortVisible, $sortVisible, handleSortChange, selectRecord } = props
  
  const [dataSource, $dataSource] = useState<any[]>([])
  const [form] = Form.useForm()
  const onOk = () => {
    const sortValue = form.getFieldValue('sort')
    
    handleSortChange({
      IndexFieldName: selectRecord.IndexFieldName,
      field: 'sort',
      type: 'update',
      value: {
        sort: sortValue,
        sortDesc: dataSource
      },
    })
    $sortVisible(false)
  }
  const changeDesc = (val, record) => {
    if (record.sortStyle == 'asc') {
      $dataSource(arr => {
        const newArr = [...arr]
        newArr[0].sortDesc = val
        return newArr
      })
    } else {
      $dataSource(arr => {
        const newArr = [...arr]
        newArr[1].sortDesc = val
        return newArr
      })
    }
  }
  const columns = [{
    title: '排序方式',
    dataIndex: 'sortStyle',
    render: (value) => {
      return value == 'asc' ? getMessage('SearchResultEngine.ascendingOrder') : getMessage('SearchResultEngine.descendingOrder')
    }
  }, {
    title: '显示文字',
    dataIndex: 'sortDesc',
    render: (value, record) => {

      return <MultilingualInput value={value} onChange={(val) => changeDesc(val, record)} />
    }
  }]

  useEffect(() => {
    if (selectRecord?.value?.sortDesc) {
      $dataSource(selectRecord?.value?.sortDesc)
    } else {
      $dataSource([{
        sortStyle: 'asc',
        sortDesc: '升序'
      }, {
        sortStyle: 'desc',
        sortDesc: '降序'
      }])
    }

  }, [selectRecord])

  return (
    <Modal
      title='编辑'
      className='sortDescModal'
      visible={sortVisible}
      onOk={onOk}
      onCancel={() => $sortVisible(false)}
      destroyOnClose
    >
      <Form form={form}>
        <Form.Item label='默认排序' name="sort" initialValue={selectRecord.value?.sort ? selectRecord.value.sort : selectRecord.value}>
          <Select
            options={[
              { label: getMessage('SearchResultEngine.ascendingOrder'), value: 'asc' },
              { label: getMessage('SearchResultEngine.descendingOrder'), value: 'desc' },
            ]}
          // onChange={(value) =>
          //   handleSortChange({
          //     IndexFieldName: record.IndexFieldName,
          //     field: 'sort',
          //     value,
          //   })
          // }
          />
        </Form.Item>
      </Form>
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={false}
        bordered
        rowKey='id'    
      />
    </Modal>
  )
}
